﻿/*************************************************************************************
 *
 * 文 件 名:   HttpClientPool
 * 描    述:   HttpClient对象池，继承自NewLife.Collections.ObjectPool 
 * 
 * 版    本：  V1.0
 * 创 建 者：  YSW 
 * 创建时间：  2022-09-19 17:42:31
 * ======================================
 * 历史更新记录
 * 版本：V          修改时间：         修改人：
 * 修改内容：
 * ======================================
*************************************************************************************/

using NewLife.Collections;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

namespace GXRTBTC.PublicClassLibrary.Model
{
    public class HttpClientPool : ObjectPool<HttpClient>
    {
        public string accessToken { get; set; } = "";
        public bool https { get; set; } = true;
        /// <summary>
        /// 超时时间，单位：秒
        /// </summary>
        public int timeout { get; set; } = 0;

        /// <summary>
        /// 创建实例
        /// </summary>
        /// <returns></returns>
        protected override HttpClient OnCreate()
        {
            HttpClientHandler handler = new HttpClientHandler();
            if (https)
            {
                handler.ServerCertificateCustomValidationCallback =
                (
                    HttpRequestMessage message,
                    X509Certificate2 cert,
                    X509Chain chain,
                    SslPolicyErrors errors
                 ) =>
                {
                    return true;
                };
            }

            //创建实例
            HttpClient httpClient = new HttpClient(handler);
            if (timeout > 0)
            {
                //Timeout默认值是 100,000 毫秒（100 秒）。若要设置无限超时，请将属性值设置为 InfiniteTimeSpan
                httpClient.Timeout = TimeSpan.FromSeconds(timeout);
            }
            if (!string.IsNullOrEmpty(accessToken))
            { 
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            }

            //返回
            return httpClient;
        }
    }
}
